using Microsoft.Practices.ObjectBuilder2;

namespace Common.Unity.Extensions.Entity
{
	public interface IEntityCreator
	{
		object CreateEntity( IBuilderContext context );
	}

	public abstract class EntityContextCreationPolicyBase<EntityContextType> : IObjectCreationPolicy
	{
		readonly EntityContextType entityContext;
		protected readonly IEntityCreator creator;

		protected EntityContextCreationPolicyBase( EntityContextType entityContext, IEntityCreator creator )
		{
			Guard.ArgumentNotNull( entityContext, "entityContext" );
			Guard.ArgumentNotNull( creator, "creator" );
			this.entityContext = entityContext;
			this.creator = creator;
		}

		public EntityContextType EntityContext
		{
			get { return entityContext; }
		}

		public IEntityCreator Creator
		{
			get { return creator; }
		}

		protected abstract object RetrieveExistingEntity( IBuilderContext context );

		object IObjectCreationPolicy.Create( IBuilderContext context )
		{
			var result = RetrieveExistingEntity( context ) ?? creator.CreateEntity( context );
			return result;
		}
	}
}